package com.x.sys.service.realm;

import org.apache.shiro.authc.AuthenticationException;


import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.x.sys.dao.AdminDao;
import com.x.sys.entity.Admin;

/**
 * 基于此对象获取用户认证和授权信息
 * */
@Component
public  class ShiroUserRealm extends AuthorizingRealm {
	/**
	 * 负责授权信息的获取和封装
	 * */
	@Autowired
	private AdminDao adminDao;
	
  /**
   * 负责认证信息的获取和封装
   * */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		//1.获取用户输入 的用户名
		UsernamePasswordToken upToken=(UsernamePasswordToken)token;
		String username=upToken.getUsername();
		System.out.println("doGetAuthenticationInfo.username="+username);
		//2.基于用户名获取用户对象
		 Admin admin=(Admin) adminDao.findAdminByUserName(username);
		 
		//3.判定用户对象是否存在
		 if(admin==null)throw new UnknownAccountException();
		//4.判定用户是否有效（是否被锁定）
		 if(admin.getA_valid()==0)throw new LockedAccountException();
		//5.封装用户认证信息(new ta的一个实现类)
		 ByteSource credentialsSalt=ByteSource.Util.bytes(admin.getA_salt());
		 System.out.println(admin.getA_password());
		 System.out.println(credentialsSalt);
		 SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(
				 admin,//principals用户身份
				 admin.getA_password(), //hashedCredentials已加密的用户的凭证
				 credentialsSalt,
				 getName());//realn名称
		return info;
		
	}
	/**
	 * 负责获取加密凭证匹配器对象*/
	@Override
	public CredentialsMatcher getCredentialsMatcher() {
		HashedCredentialsMatcher hMatcher=new HashedCredentialsMatcher();
		hMatcher.setHashAlgorithmName("MD5");
		hMatcher.setHashIterations(1);
	return hMatcher;
}
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// TODO Auto-generated method stub
		return null;
	}

	}




